package com.msl.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.msl.MslApp;
import com.msl.R;
import com.msl.adapter.ProductrkAdapter;
import com.msl.base.BaseFragment;
import com.msl.bean.AbDcodeBean;
import com.msl.bean.AbStateBean;
import com.msl.scan.BroadcastConfig;
import com.msl.tool.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


public class Fragment117SCRK1 extends BaseFragment {
    String tag = "Fragment117SCRK1";
    protected View mView = null;
    @Bind(R.id.tvs)
    TextView tvs;
    @Bind(R.id.etcode)
    EditText etcode;
    @Bind(R.id.bt)
    Button bt;
    @Bind(R.id.btf)
    Button btf;
    @Bind(R.id.ll)
    LinearLayout ll;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.tv1)
    TextView tv1;
    RelativeLayout rl;
    @Bind(R.id.list)
    ListView list;
    @Bind(R.id.sws)
    Switch sws;
    @Bind(R.id.swsf)
    Switch swsf;


    private AbStateBean abStateBean;
    private List<AbStateBean.Data> listdata = new ArrayList<AbStateBean.Data>();
    private ProductrkAdapter sa;
    private boolean flag = false;
    private AbDcodeBean abDcodeBean = new AbDcodeBean();
    private AbDcodeBean abDcodeBeantemp = new AbDcodeBean();
    private List<AbDcodeBean.DataBean> abDcodeBean1;
    private int index = 0;
    private boolean deletefalse = false;
    private boolean forcefalse = false;
    private String tempcode="";

    protected BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MslApp.datac)) {
                AbDcodeBean temp = (AbDcodeBean) intent.getSerializableExtra(MslApp.codedea);
                abDcodeBean1.clear();
                abDcodeBean1.addAll(temp.getData());
                sa.notifyDataSetChanged();
            } else if (intent.getAction().equals(BroadcastConfig.CUSTOM_NAME)) {
                Log.e(tag, "onReceive");
                if(MslApp.id1.length()==0 || MslApp.id2.length()==0 || MslApp.id3.length()==0)
                {
                    ToastUtils.showSingleToast(getContext(),"基础信息为空 扫描失败");
                    return;
                }
                //删除条码
                if(deletefalse)
                {
//                    String str = "";
//                    if (!flag) {
//                        str = "1";
//                    } else {
//                        str = "2";
//                    }
                    deletecode(MslApp.url + "?action=DeleteCode&cid=" + MslApp.sSharedPreferences.getString(MslApp.cidk, "")
                            + "&userID=" + MslApp.sSharedPreferences.getInt(MslApp.userID, 0)
                            + "&storeID=" + MslApp.sSharedPreferences.getInt(MslApp.storeID, 0)
                            + "&billcode=" + abDcodeBean.getData().get(index).getBillcode()
                            + "&code=" + intent.getStringExtra("scannerdata")
                            + "&codeType=" + "1"
                 );
                }
                else
                {
//                    if(tempcode.equals(intent.getStringExtra("scannerdata")))
//                    {
//                        return;
//                    }
//                    tempcode = intent.getStringExtra("scannerdata");
//                String str = "";
//                if (!flag) {
//                    str = "1";
//                } else {
//                    str = "2";
//                }
//                String code =   abDcodeBean1.get(index).getBillcode()+ ","+abDcodeBean1.get(index).getProductID()+","+
//                        str+","+intent.getStringExtra("scannerdata")+","+abDcodeBean1.get(index).getSubBillCode()+","+abDcodeBean1.get(index).getManualNums();
                String code = abDcodeBean.getData().get(index).getBillcode() + "," + abDcodeBean1.get(index).getProductID() + "," +
                        "1" + "," + intent.getStringExtra("scannerdata") + "," + abDcodeBean1.get(index).getSubBillCode() + "," + "0"
                        +","+forcefalse;
                //Log.e(tag,code);
                MslApp.listcode.add(code);
                swsf.setChecked(false);
                forcefalse= false;
                }
            } else if (intent.getAction().equals("netcsucc")) {
                tvs.setText("网络状态:正常");
            } else if (intent.getAction().equals("netcfail")) {
                tvs.setText("网络状态:异常");
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragments117scrk1, null);
        ButterKnife.bind(this, mView);

//        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//        try {
//            Class<EditText> cls = EditText.class;
//            Method setShowSoftInputOnFocus;
//            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus",
//                    boolean.class);
//            setShowSoftInputOnFocus.setAccessible(true);
//            setShowSoftInputOnFocus.invoke(etcode, false);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        initBroadcastReciever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MslApp.datac);
        intentFilter.addAction(BroadcastConfig.CUSTOM_NAME);
        intentFilter.addAction("netcsucc");
        intentFilter.addAction("netcfail");
        getActivity().registerReceiver(mBroadcastReceiver, intentFilter);
        abDcodeBean = (AbDcodeBean) getActivity().getIntent().getSerializableExtra(MslApp.codedea);
        //sa = new ProductAdapter(getContext(),abDcodeBean.getData());
        abDcodeBean1 = abDcodeBean.getData();
        tv1.setText(abDcodeBean1.get(0).getTuoCaseNums()+"");
        sa = new ProductrkAdapter(getContext(), abDcodeBean1);
        list.setAdapter(sa);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sa.setSelectedPosition(position);
                sa.notifyDataSetInvalidated();
                index = position;
            }
        });

//        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//                index = i;
//                sa.setSelectedPosition(index);
//                sa.notifyDataSetInvalidated();
//                NumDialog nDialog = new NumDialog(getContext(), R.style.Dialog1, new NumDialog.PriorityListener() {
//                    @Override
//                    public void setActivityText(String string) {
//                        if (Integer.parseInt(string) + abDcodeBean.getData().get(index).getsScanNums() > abDcodeBean.getData().get(index).getyScanNums()) {
//                            ToastUtils.showSingleToast(getActivity(), "输入数字超过产品最大应扫量");
//                            return;
//                        }
//                        ;
//                        waitDialog.show();
//                        snum(MslApp.url + "?action=UpdateCodes_Deatil&cid=" + MslApp.sSharedPreferences.getString(MslApp.cidk, "")
//                                + "&userID=" + MslApp.sSharedPreferences.getInt(MslApp.userID, 0)
//                                + "&storeID=" + MslApp.sSharedPreferences.getInt(MslApp.storeID, 0)
//                                + "&billcode=" + abDcodeBean.getData().get(index).getBillcode()
//                                + "&productID=" + abDcodeBean.getData().get(index).getProductID()
//                                + "&codeType=" + "-1"
//                                + "&codes=" + ""
//                                + "&manualNums=" + string
//                                + "&subBillCode=" + abDcodeBean.getData().get(index).getSubBillCode().replace("+", "%2B")
//                                + "&storeInfo=" + MslApp.id1
//                                + "&billChangeType=" + MslApp.id2
//                                + "&transactionCode=" + MslApp.id3
//                                + "&storeOtherInfo=" + MslApp.id1
//                        );
//                    }
//                });
//                WindowManager.LayoutParams lp = nDialog.getWindow().getAttributes();
//                lp.gravity = Gravity.CENTER;
//                nDialog.show();
//                return false;
//            }
//        });

        return mView;
    }

    void snum(String url) {
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    waitDialog.dismiss();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {//回调的方法执行在子线程。
                        result = response.body().string();
                        Log.e(tag, result);
                        waitDialog.dismiss();
                        handler.sendEmptyMessage(1);
                    } else {
                        Log.e(tag, "获取数据失败了" + response.code());
                        waitDialog.dismiss();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            waitDialog.dismiss();
        }
    }


    void deletecode(String url) {
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    waitDialog.dismiss();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {//回调的方法执行在子线程。
                        result = response.body().string();
                        Log.e(tag, result);
                        waitDialog.dismiss();
                        handler.sendEmptyMessage(0);
                    } else {
                        Log.e(tag, "获取数据失败了" + response.code());
                        waitDialog.dismiss();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            waitDialog.dismiss();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    abDcodeBeantemp = gson.fromJson(result, AbDcodeBean.class);
                    if (abDcodeBeantemp.getErrcode() == 0) {
                        abDcodeBean = abDcodeBeantemp;
                        abDcodeBean1.clear();
                        abDcodeBean1.addAll(abDcodeBean.getData());
                        sa.notifyDataSetChanged();
                    }
                    else
                    {
                        ToastUtils.showSingleToast(getActivity(),abDcodeBeantemp.getErrmsg());
                        MediaPlayer mediaPlayer01;
                        mediaPlayer01 = MediaPlayer.create(getActivity(), R.raw.cf);
                        mediaPlayer01.start();
                    }
                    break;
                case 1:
                   ToastUtils.showSingleToast(getActivity(),"开启强制拼托");
                    break;
                default:
                    break;

            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onResume() {
        Log.e(tag, "onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.e(tag, "onPause");
        super.onPause();
    }

    @OnClick({R.id.bt,R.id.btf,R.id.sws,R.id.swsf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt:
                String code = etcode.getText().toString();
                if (code.length() == 0) {
                    ToastUtils.showSingleToast(getContext(), "请输入条码");
                    return;
                }
                if (code.length() != 14 && code.length() != 16) {
                    ToastUtils.showSingleToast(getContext(), "请输入14位或16位条码");
                    return;
                }
//                String str = "";
//                if (!flag) {
//                    str = "1";
//                } else {
//                    str = "2";
//                }
//                code =   abDcodeBean.getData().get(index).getBillcode()+ ","+abDcodeBean.getData().get(index).getProductID()+","+
//                        str+","+code+","+abDcodeBean.getData().get(index).getSubBillCode()+","+abDcodeBean.getData().get(index).getManualNums();
                code = abDcodeBean.getData().get(index).getBillcode() + "," + "-1" + "," +
                        "1" + "," + code + "," + "" + "," + "0";
                MslApp.listcode.add(code);
                etcode.setText("");
                break;
            case R.id.btf:
                snum(MslApp.url + "?action=QiangZhiPingTuo&cid=" + MslApp.sSharedPreferences.getString(MslApp.cidk, "")
                        + "&userID=" + MslApp.sSharedPreferences.getInt(MslApp.userID, 0)
                        + "&storeID=" + MslApp.sSharedPreferences.getInt(MslApp.storeID, 0)
                        + "&billcode=" + abDcodeBean.getData().get(index).getBillcode()
                );
                break;
            case R.id.sws:
                deletefalse = !deletefalse;
                break;
            case R.id.swsf:
                forcefalse = !forcefalse;
                break;
        }
    }

}
